<?php

namespace app\service\payment\gateway;

use app\libs\StripeSDK\Builder\CustomerBuilder;
use app\libs\StripeSDK\Builder\PaymentLinksBuilder;
use app\libs\StripeSDK\StripeAPI;
use app\model\Notify;
use app\model\Orders;
use think\helper\Arr;
use think\Request;

class StripeService extends PaymentBase implements PaymentInterface
{

    public function placeOrder(Orders $order, Request $request)
    {
        $log = null;
        try {
            $stripe = new StripeAPI($order->payment);
            # 1.创建用户
            $customerBuilder = new CustomerBuilder($order,$request);
            $customerRes = $stripe->getStripe()->customers->create($customerBuilder->toArray());
            $customer = $customerRes->toArray();
            if (empty($customer)) throw new \Exception('create stripe customer error');
            $builder = new PaymentLinksBuilder($order,$request);
            $session = $builder->toArray();
            $session['customer'] = $customer['id'];
            $response = $stripe->getStripe()->checkout->sessions->create($session);
            $result = $response->toArray();
           $log = Notify::saveParams(
                $order->id,
                ['params'=>$session,'result'=>$result,]
                ,Notify::TYPE_PLACE_ORDER,
                $order->pay_method);
            $transaction_id = Arr::get($result,'id','');
            if (empty($transaction_id)) throw new \Exception('create stripe order error');
            $approval_url = $result['url'];
            $order->trade_no = $transaction_id;
            $order->save();
            return compact(
                'transaction_id',
                'approval_url'
            );
        }catch (\Exception $e){
            if($log){
                $logParams = $log->params;
                $logParams['error'] = $e->getMessage();
                $log->save();
            }
            throw $e;
        }

    }

    public function confirmPayment()
    {
        // TODO: Implement confirmPayment() method.
    }

    public function repurchase(Orders $order, Request $request){
        //todo
        return [];
    }
}